import Vue from 'vue'
import router from '../router/index'
import {asyncRouter} from './asyncRouter.js'
import store from './store'

export default function () {
  /**
   * 全局变量
   * @type {{}}
   */
  Vue.prototype.app = {
    tabList: [],
    tabActive: 1
  }
  /**
   * 全局路由跳转
   * @param msg
   */
  Vue.prototype.jump = function (path, title, query) {
    activeTab(path, title, query)
  }
  /**
   *移除Tab
   */
  Vue.prototype.removeTab = function (targetName) {
    // console.log(targetName);
    let tabs = store.state.tab.list
    if (targetName == '/home/welcome') {
      return
    }
    // console.log("开始")
    // console.log( store.state.tab.list )
    store.state.tab.list = tabs.filter(tab => tab.name !== targetName)

    let index = store.state.tab.list.length - 1
    if (index < 0) {
      index = 0
    }
    let target = store.state.tab.list[index]
    activeTab(target.path, target.title)

  },
    /**
     * 深度拷贝
     */
    Vue.prototype.cloneDeep = function (templateData) {
      // templateData 是要复制的数组或对象，这样的数组或者对象就是指向新的地址的
      return JSON.parse(JSON.stringify(templateData))
    }
  router.beforeEach((to, from, next) => {
    // if (to.path == from.path && to.path != '/') {
    //     return
    // }
    console.log(asyncRouter.hasName(to.path))
    if (!asyncRouter.hasName(to.path)) {
      //只能注册子路由
      router.options.routes[0].children = router.options.routes[0].children.concat([
        {
          path: `${to.path}`,
          component: resolve => require(['@/pages/' + to.path.replace('/pages/', '')], resolve)
        }
      ])
      router.addRoutes(router.options.routes)
      next(to.path)
    } else {
      next()
    }
  })

  //激活标签
  function activeTab (path, title, query) {
    let routePath = path.split('?')[0]
    if (!asyncRouter.hasName(path)) {
      asyncRouter.addRouter(routePath)
    }

    router.push({
      path: routePath,
      query: query
    })
    let existTabList = false
    for (let i in store.state.tab.list) {
      let tab = store.state.tab.list
      if (tab[i].path == path) {
        existTabList = true
      }
    }
    if (!existTabList) {
      console.log('注册标签')
      store.state.tab.list.push({
        title: title,
        path: path,
        name: path,
        query: query,
      })
    }
    store.state.tab.active = path
  }
}
